﻿using System;
using Internal.KuiHuaBaoDian.Services.Battle.StateMachine;
using KuiHuaBaoDian.Services.Battle.Entity;

namespace KuiHuaBaoDian.Services.Battle.StateMachine {

    /// <summary>
    /// 由<see cref="UnityEngine.Animator"/>进行显示播放的状态机，但只会播放其默认的动画剪辑
    /// </summary>
    public interface IBattleEntityStateMachine_AnimatorDefault : IBattleEntityStateMachine {
    }

    [Implement(typeof(IBattleEntityStateMachine_AnimatorDefault))]
    internal sealed class KHBD_BattleEntityStateMachine_AnimatorDefault : KHBD_Object, IBattleEntityStateMachine_AnimatorDefault, IBattleEntityStateMachineInternal_Animator {

        private IBattleEntityAssetVehicle<UnityEngine.Animator> m_StateVehicle;
        private UnityEngine.Animator m_Animator;
        private IBattleEntityStateSpeedGetter m_SpeedGetter;

        public BattleEntityState State { get; set; }

        public bool IsInitialized => m_Animator != null;

        private float m_PlaySpeed;

        void IBattleEntityStateMachineInternal_Animator.Initialize(IBattleEntityAssetVehicle<UnityEngine.Animator> stateVehicle, IBattleEntityStateSpeedGetter speedGetter) {
            UnityEngine.Assertions.Assert.IsNotNull(stateVehicle);
            UnityEngine.Assertions.Assert.IsNotNull(speedGetter);

            m_StateVehicle = stateVehicle;
            m_SpeedGetter = speedGetter;
            m_StateVehicle.Loaded += OnStateVehicleLoaded;
            OnStateVehicleLoaded();
        }

        protected override void Dispose() {
            m_Animator = null;
            m_SpeedGetter = null;
            m_StateVehicle.Loaded -= OnStateVehicleLoaded;
            m_StateVehicle = null;
        }

        private void OnStateVehicleLoaded() {
            if (m_StateVehicle.Content == null) {
                return;
            }
            m_Animator = m_StateVehicle.Content;
            Play(m_PlaySpeed);
        }

        public void Play(float speed) {
            m_PlaySpeed = speed;

            if (!IsInitialized) {
                return;
            }

            var stateSpeed = m_SpeedGetter.GetValue(State);
            var playSpeed = stateSpeed * speed;
            if (playSpeed < 0f) {
                playSpeed = 0f;
            }
            m_Animator.speed = playSpeed;
        }
    }
}
